// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RollingArray.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Framework
{
    #region Usings

    using System;
    using System.Collections.Generic;

    using Org.OpenTrader.Framework.Interfaces;

    #endregion

    /// <summary>
    /// An O(1) implementation of IRollingArray<typeparamref name="T"/>. No elements are recopied, 
    /// instead indices of first and last are held appropriately
    /// </summary>
    /// <typeparam name="T">
    /// The data type
    /// </typeparam>
    public class RollingArray<T> : IRollingArray<T>
    {
        #region Constants and Fields

        /// <summary>
        /// the list where things will be stored
        /// </summary>
        private readonly List<T> list;

        /// <summary>
        /// The locker.
        /// </summary>
        private readonly ILocker locker = new Locker();

        /// <summary>
        /// The first element
        /// </summary>
        private int first;

        /// <summary>
        /// The last element
        /// </summary>
        private int last;

        /// <summary>
        /// The realSize.
        /// </summary>
        private int realSize;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="RollingArray{T}"/> class. 
        /// Creates a rolling array of T with given capacity
        /// </summary>
        /// <param name="c">
        /// Capacity, that is maximal size of the table, Count will grow from 0 to capacity when adding elements
        /// </param>
        public RollingArray(int c)
        {
            this.list = new List<T>(c);
            this.realSize = 0;
            this.first = 0;
            this.last = -1;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the capacity of the array
        /// </summary>
        public int Capacity
        {
            get
            {
                return this.list.Capacity;
            }
        }

        /// <summary>
        /// Gets the count, thas is the real number of elements in the range [0;capacity]
        /// </summary>
        public int Count
        {
            get
            {
                return this.realSize;
            }
        }

        #endregion

        #region Indexers

        /// <summary>
        /// Redefines the [] indexer. User can only get/set upto real number of elements (which is not capacity)
        /// </summary>
        /// <param name="offset">index of the value</param>
        /// <returns>The required value</returns>
        public T this[int offset]
        {
            get
            {
                using (this.locker.Lock())
                {
                    if (this.realSize < this.list.Count)
                    {
                        return this.list[offset];
                    }
                    else if (offset < this.realSize)
                    {
                        return this.list[(this.first + offset) % this.list.Count];
                    }

                    throw new IndexOutOfRangeException();
                }
            }

            set
            {
                throw new Exception("RollingArray doesn't allow to change previously added elements");

                // using (this.locker.Lock())
                // {
                // if (this.realSize < this.list.Count)
                // {
                // this.list[offset] = value;
                // }
                // else if (offset < this.realSize)
                // {
                // this.list[(this.first + offset) % this.list.Count] = value;
                // }
                // throw new IndexOutOfRangeException();
                // }
            }
        }

        #endregion

        #region Implemented Interfaces

        #region IRollingArray<T>

        /// <summary>
        /// Add some T element to the array. The array grows from 0 to full size.
        /// When the array is full, the oldest data is removed and returned to user
        /// Indexes remain stable in time, that is
        ///   array[0] is always the oldest element
        ///   array[size-1] is always the newest element
        /// </summary>
        /// <param name="data">
        /// Element to add
        /// </param>
        /// <param name="removed">
        /// The removed.
        /// </param>
        /// <returns>
        /// RollingArray&lt;T&gt;.Removed instance if some element had to be removed, null otherwise
        /// </returns>
        public T Add(T data, ref bool removed)
        {
            removed = false;
            using (this.locker.Lock())
            {
                if (this.realSize >= this.list.Capacity)
                {
                    // already at full capacity, eject oldest
                    var previousFirst = this.first;
                    this.first = (previousFirst + 1) % this.list.Count;
                    this.last = (this.last + 1) % this.list.Count;
                    var save = this.list[previousFirst];
                    this.list[previousFirst] = data;
                    removed = true;
                    return save;
                }

                // grow
                this.last++;
                this.list.Add(data); // real version is this.list.Add not this.Add. Beware of stupid refactoring with R#
                this.realSize++;
                return default(T);
            }
        }

        /// <summary>
        /// Add and forget about lost value if necessary
        /// </summary>
        /// <param name="data">
        /// The data to add
        /// </param>
        public void Add(T data)
        {
            var b = false;
            this.Add(data, ref b);
        }

        #endregion

        #endregion
    }
}